package com.simple.web.controller.llm;

import com.github.zuihou.base.R;
import com.simple.common.annotation.Anonymous;
import com.simple.llm.domain.dto.LLMMessageDTO;
import com.simple.llm.domain.dto.NormalChatDTO;
import com.simple.llm.domain.dto.StreamChatDTO;
import com.simple.llm.domain.vo.LLMResponseVO;
import com.simple.llm.service.LLMContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.List;

@Slf4j
@RequestMapping("/aiToyLLM")
@RestController
public class AIToyLLMController {
    public static final String REDIS_STREAM_CHAT_KEY = "llmserver-stream-chat:";
    @Resource
    private LLMContext llmContext;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/chatId")
    public R<String> getChatId(@RequestBody StreamChatDTO streamChatDTO) {
        String chatId = llmContext.streamRecord(streamChatDTO);
        streamChatDTO.setMessages(null);
        streamChatDTO.setChatId(chatId);
        redisTemplate.opsForValue().set(REDIS_STREAM_CHAT_KEY + chatId, streamChatDTO, Duration.ofMinutes(30));
        return R.success(chatId);
    }


    @GetMapping("/chatMessages/{chatId}")
    public R<List<LLMMessageDTO>> getMessagesByChatId(@PathVariable String chatId){
        return R.success(llmContext.getMessagesByChatId(chatId));
    }


    @PostMapping("/chat")
    @Anonymous
    public R<LLMResponseVO> chat(@RequestBody NormalChatDTO normalChatDTO){
        return llmContext.chat(normalChatDTO);
    }

    @PostMapping("/streamChat")
    public ResponseBodyEmitter streamChat(@RequestBody StreamChatDTO streamChatDTO, HttpServletResponse response) {
        Long userId = 0L;
        if(userId == null){
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        log.info("当前登录的用户:{}",userId);
        Object obj = redisTemplate.opsForValue().get(REDIS_STREAM_CHAT_KEY + streamChatDTO.getChatId());
        if(obj instanceof StreamChatDTO){
            streamChatDTO = (StreamChatDTO)obj;
            if (!streamChatDTO.getCreateUser().equals(userId.toString())) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }
            List<LLMMessageDTO> messagesByChatId = llmContext.getMessagesByChatId(streamChatDTO.getChatId());
            streamChatDTO.setMessages(messagesByChatId);
            return llmContext.streamChat(streamChatDTO, response, o -> {
                // 后续业务预留处理
            });
        }
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

}
